package com.gx.mvp.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import com.gx.mvp.R;
import com.wang.avi.AVLoadingIndicatorView;

/**
 * 正在加载
 *
 * Created by Guoxin on 2019/12/05.
 */
public class CustomLoadDialog {
    private Context                mContext;
    private Dialog                 mDialog;
    private AVLoadingIndicatorView mAVLoadingIndicatorView;

    public CustomLoadDialog(Context context) {
        this.mContext = context;
        this.init();
    }

    private void init() {
        this.mDialog = new Dialog(this.mContext, R.style.CustomLoadingDialogStyle);
        View loadingView = LayoutInflater.from(this.mContext).inflate(R.layout.custom_loading_dialog, null);
        this.mAVLoadingIndicatorView = loadingView.findViewById(R.id.loading_progress);
        this.mAVLoadingIndicatorView.setIndicator("BallSpinFadeLoaderIndicator");
        this.mAVLoadingIndicatorView.setIndicatorColor(mContext.getColor(R.color.white));
        this.mAVLoadingIndicatorView.setBackgroundColor(mContext.getColor(R.color.transparent));
        this.mAVLoadingIndicatorView.show();
        this.mDialog.setContentView(loadingView);
    }

    /**
     * 加载指定布局
     *
     * @param layoutId
     */
    public void setLoadingView(int layoutId) {
        View loadingView = LayoutInflater.from(this.mContext).inflate(layoutId, null);
        this.mDialog.setContentView(loadingView);
    }

    public Dialog getDialog() {
        return mDialog;
    }

    /**
     * 显示
     */
    public void show() {
        if (null != this.mDialog && !this.mDialog.isShowing()) {
            this.mDialog.show();
        }
    }

    /**
     * 隐藏
     */
    public void hide() {
        if (null != this.mDialog && this.mDialog.isShowing()) {
            this.mDialog.dismiss();
        }
    }

    /**
     * 销毁
     */
    public void destroy() {
        if (null != this.mDialog && this.mDialog.isShowing()) {
            this.mDialog.dismiss();
        }
        this.mDialog = null;
    }

    /**
     * 是否正在显示
     */
    public boolean isShowing() {
        return null != this.mDialog && this.mDialog.isShowing();
    }

    /**
     * 设置触摸是否取消对话框
     */
    public void setCanceledOnTouchOutside(boolean cancel) {
        if (null != this.mDialog) {
            this.mDialog.setCanceledOnTouchOutside(cancel);
        }
    }

    /**
     * 设置按键key监听（比如监听是否点击返回键）
     *
     * @param listener
     */
    public void setOnKeyListener(DialogInterface.OnKeyListener listener) {
        mDialog.setOnKeyListener(listener);
    }
}
